/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { BaseCommand, CommandDialog, S3Inst, StringUtils } from '@amcax/base';
import { InboxOutlined } from '@ant-design/icons';
import { loadEmit } from '@app-base/common/events/CoreEvent';
import { ctx2 } from '@app-base/module';
import { wsApi } from '@app-base/server';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import type { UploadProps } from 'antd';
import { Checkbox, Upload } from 'antd';
import i18n from 'i18next';
import { useEffect, useState } from 'react';
import styled from 'styled-components';

const { Dragger } = Upload;

const StyledLayout = styled.div`
  display: flex;
  padding: 10px;

  & .ant-upload-drag {
    width: 400px;
    height: auto;
  }
`;

interface ImportDialogProps {
  title: string;
  onClose: () => void;
}

function ImportDialog({ title, onClose }: ImportDialogProps) {
  const [createCurve, setCreateCurve] = useState(true);
  const [createPoint, setCreatePoint] = useState(false);

  useEffect(() => {
    if (createCurve === false && createPoint === false) {
      MessageTip.warning('必须至少启用一个选项');
      setCreateCurve(true);
    }
  }, [createCurve, createPoint]);

  const uploadFile = (options) => {
    loadEmit(true);
    const { file, onSuccess, onProgress } = options;
    const fileTypeIndex = file.name.split('.').length - 1;
    const fileType = file.name.split('.')[fileTypeIndex];
    const ossfile = StringUtils.randomString(10) + '.' + fileType;
    S3Inst.uploadFile(
      'cad',
      ossfile,
      file,
      (progress: { loaded: number; total: number }) => {
        const percentage = Math.floor((progress.loaded * 100) / progress.total);
        onProgress({ percent: percentage }, file);
      },
      async (data: { bucket: string; path: string }) => {
        const bucket = data.bucket;
        const path = data.path;
        await doRender('s3://' + bucket + path, fileType);
        onSuccess({ name: path, status: 'done', file });
      },
    );
  };

  const props: UploadProps = {
    name: 'file',
    multiple: true,
    accept: '.txt',
    beforeUpload: (file) => {
      const size = 10; // 单位MB
      const validSize = file.size / 1024 / 1024 < size;
      if (!validSize) {
        MessageTip.error(`文件必须小于 ${size}MB！`);
        return Upload.LIST_IGNORE; // 不加入fileList
      }
      const extension = '.' + file.name.split('.').pop()?.toLowerCase();
      const isValidType = extension === '.txt';
      if (!isValidType) {
        MessageTip.error(`${file.name} 文件类型不支持，请选择正确的文件类型`);
      }
      return isValidType || Upload.LIST_IGNORE;
    },
    onChange(info: any) {
      if (info.file.status !== 'uploading') {
        // console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        // console.log(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        MessageTip.error(`${info.file.name} 文件上传失败`);
      }
    },
    customRequest: uploadFile,
    onDrop(/*e*/) {
      // console.log('Dropped files', e.dataTransfer.files);
    },
  };

  const doRender = async (filepath: string, fileType: string) => {
    const params = {
      t: filepath,
      curve: createCurve,
      point: createPoint,
    };
    try {
      if (fileType === 'txt') {
        await wsApi.import2DPoints(params);
      }
    } catch (e: any) {
      MessageTip.error(e.message);
      loadEmit(false);
    }

    ctx2.viewer.fitObjectView();
    onClose();
  };

  return (
    <CommandDialog
      title={title}
      onClose={onClose}
      placement='topLeft'>
      <StyledLayout>
        <div>
          <Dragger {...props}>
            <p className='ant-upload-drag-icon'>
              <InboxOutlined />
            </p>
            <p className='ant-upload-text'>{i18n.t('uploader.drag_text')}</p>
            <p className='ant-upload-hint'>
              {'支持上传的文件类型：翼型点列表.txt'}
            </p>
          </Dragger>
          <Checkbox
            style={{ marginTop: 8 }}
            checked={createCurve}
            onChange={(e) => setCreateCurve(e.target.checked)}>
            自动拟合曲线
          </Checkbox>
          <Checkbox
            style={{ marginTop: 8 }}
            checked={createPoint}
            onChange={(e) => setCreatePoint(e.target.checked)}>
            创建点列表
          </Checkbox>
        </div>
      </StyledLayout>
    </CommandDialog>
  );
}

export const cmdImportAirfoil: BaseCommand = {
  id: 'CmdImport',
  label: '导入翼型点',
  icon: 'commands/feature/import-airfoil',
  noHighlight: true,

  create: (label: string, onClose: () => void) => (
    <ImportDialog
      title={i18n.t(label)}
      onClose={onClose}
    />
  ),
};
